<script setup lang="ts">
import { provide, reactive } from "vue";
import { defaultOptions, TOAST_PROVIDED_KEY } from "./api.ts";
import type { ToastApiInjection } from "./api.ts";

const data = reactive({
    visible: false,
    content: ""
});

let hideTimeoutId: any;

const apiInjection: ToastApiInjection = {
    info(content, options) {
        apiInjection.show(Object.assign({
            type: "info",
            content
        }, options));
    },
    show(options) {
        options = Object.assign({}, defaultOptions, options);
        if (hideTimeoutId) {
            clearTimeout(hideTimeoutId);
        }
        data.visible = true;
        data.content = options.content;
        hideTimeoutId = setTimeout(() => {
            data.visible = false;
        }, options.duration);
    }
}

provide(TOAST_PROVIDED_KEY, apiInjection);

</script>

<template>
    <transition name="toast" mode="out-in">
        <div class="toast" v-show="data.visible">{{ data.content }}</div>
    </transition>
    <slot></slot>
</template>

<style scoped>
.toast {
    @apply rounded-xl px-5 py-2 break-all;
    position: fixed;
    z-index: 9999;
    top: 50%;
    left: 50%;
    max-width: 90vw;
    transform: translate(-50%, -50%);
    color: var(--sys-toast-text-color);
    background: var(--sys-toast-background);
}


.toast-enter-active,
.toast-leave-active {
    transition: opacity 0.2s ease;
}

.toast-enter-from,
.toast-leave-to {
    opacity: 0;
}
</style>